/**
 * 
 */

define([ 'angular'
		,'ocLazyLoad'
    
//         ,'angularAnimate'
         ,'uiRouter'
         ,'uiBootstrap'
         
//         ,'angularSanitize'
//         ,'wysiwyg'

         ,'BizData'
//         ,'services'
         ,'directives'
//         ,'filters'
         ,'controllers'
//         ,'subcontrollers'
         ,'js/center/center.js' 
        
//         ,'js/profile/page.js' 
//         ,'js/password/page.js' 
//         ,'js/email/page.js' 

//         ,'js/sysInfoOrg/list.js' 
//         ,'js/sysInfoOrg/selectMulti.js' 
           
//         ,'js/role/list.js' 
//         ,'js/role/single.js' 
//         ,'js/role/selectMulti.js' 


//         ,'js/orgauth/treeList.js' 
         

//         ,'js/messages/list.js' 
//         ,'js/messages/single.js' 
         
//         ,'js/org/single.js' 
//         ,'js/ogn/center.js' 
         
//         ,'js/workcenter/list.js' 
//         ,'js/workcenter/single.js' 

//         ,'js/saleOffer/list.js' 

//         ,'js/schedule/list.js' 

         ], function(angular) {
	
	// 定义模块
	var app = angular.module('backcenter', [
											'oc.lazyLoad'
//	                                        ,'ngAnimate'
	                                        ,'ui.router'
	                                        ,'ui.bootstrap'
	                                        
//	                                        ,'ngSanitize'
//	                                        ,'ngWYSIWYG'

	                                        ,'app.BizData'
//	                                         ,'app.services'
	                                         ,'app.directives'
//	                                         ,'app.filters'
	                                         ,'app.controllers'
//	                                         ,'app.subcontrollers'
	                                         ,'app.subcontrollers'
	                                         
//	                                         ,'backcenter.personProfile' 
//	                                         ,'backcenter.personPassword' 
//	                                         ,'backcenter.personEmail' 
	                                         
//	                                         ,'backcenter.sysInfoOrgList' 
//	                                         ,'backcenter.sysInfoOrgSelectMulti' 
	                                         
//	                                         ,'backcenter.roleList'
//	                                         ,'backcenter.roleSingle'
//	                                         ,'backcenter.roleSelectMulti'


//	                                         ,'backcenter.orgauth'
	                                         

//	                                         ,'backcenter.messagesList'
//	                                         ,'backcenter.messagesSingle'
	                                         
//	                                         ,'backcenter.ognSingle'
//	                                         ,'backcenter.ognCenter'

//	                                         ,'backcenter.workcenterList'
//	                                         ,'backcenter.workcenterSingle'

//	                                         ,'backcenter.saleOfferList'

//	                                         ,'backcenter.schedule'

	                                         ]);
	
	app.constant('aaa', {
		imgEndpointUrl: 'http://www.iune.cn'
		,AMQ_URL: 'ws://www.iune.cn'
//		,AMQ_URL: 'ws://localhost'
	});


	
	//anrular-ui-router
	app.run(
			  ['$rootScope', '$state', '$stateParams',
			    function ($rootScope,   $state, $stateParams) {

			    // It's very handy to add references to $state and $stateParams to the $rootScope
			    // so that you can access them from any scope within your applications.For example,
			    // <li ng-class="{ active: $state.includes('contacts.list') }"> will set the <li>
			    // to active whenever 'contacts.list' or one of its decendents is active.
			    $rootScope.$state = $state;
			    $rootScope.$stateParams = $stateParams;
			    
				//头部文件菜单的点击状态更改//////////////////////////////////////////////////
			    $rootScope.navActive=function(){
					//获取请求路径
					//获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
					$rootScope.curWwwPath=window.document.location.href;
					
				    //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
					$rootScope.pathName=window.document.location.pathname;
					$rootScope.pos=$rootScope.curWwwPath.indexOf($rootScope.pathName);
				    //获取主机地址，如： http://localhost:8083
					$rootScope.localhostPath=$rootScope.curWwwPath.substring(0,$rootScope.pos);
				    //获取带"/"的项目名，如：/uimcardprj
//					$rootScope.projectName=$rootScope.pathName.substring(0,$rootScope.pathName.substr(1).indexOf('/')+1);
//					console.log('$rootScope.curWwwPath-->>',$rootScope.curWwwPath);
//					console.log('$rootScope.pathName-->>',$rootScope.pathName);
//					console.log('$rootScope.localhostPath-->>',$rootScope.localhostPath);
//					console.log('$rootScope.pos-->>',$rootScope.pos);
//					console.log('$rootScope.projectName-->>',$rootScope.projectName);
					
				};
				
				//$rootScope.navActive();
				
//				$rootScope.projectName='/control';//项目名称为空时使用，在eclipse中将项目名称设置"/"
				$rootScope.projectName='/u2';//项目名称为空时使用，在eclipse中将项目名称设置"/"
				$rootScope.getProjectName = function(){
					return $rootScope.projectName;
				}
				
//				$rootScope.serviceName = '/control';//数据服务接入点
				$rootScope.serviceName = '/u2';//数据服务接入点
				$rootScope.getServiceName = function(){
					return $rootScope.serviceName;
				}
	    		
	    		//解析图片
	    	    $rootScope.filePathInit = function(row){
	    	    	if(row.images==null) return '';
	    	    	var imagesArray = angular.fromJson(row.images.value);
//	    	    	var imagesArray = angular.fromJson(row.images);
//	    	    	console.log('imagesArray-->',imagesArray);
//	    	    	console.log('$scope.filePath-->',$scope.filePath);
	    	    	return $rootScope.imagesUrl(imagesArray);
	    	    };
	    	    
			    $rootScope.imagesUrl = function(imagesArray){
//			    	console.log('imagesArray-->',imagesArray);
	    	    	if(imagesArray!=null){
	    	    		var filePath= OssEndpoint.imgEndpointUrl+'/'+imagesArray[0].groupName+'/'+imagesArray[0].remoteFileName;
	    	    	}else{
	    	    		var filePath='';
	    	    	}
			//    	console.log('$scope.filePath-->',$scope.filePath);
			    	return filePath;
			    };


	    		//提示信息
	    		/////////////////////////////////////////////////////////////////////////////////////////////
	    		$rootScope.alerts = [
//	    		                 { type: 'danger', msg: 'Oh snap! Change a few things up and try submitting again.' },
//	    		                 { type: 'success', msg: 'Well done! You successfully read this important alert message.' }
	    		               ];

	    		$rootScope.addAlert = function(type,message) {
	    			$rootScope.alerts.push({type: type, msg: message});
	    		};

	    		$rootScope.closeAlert = function(index) {
	    			$rootScope.alerts.splice(index, 1);
	    		};
	    		/////////////////////////////////////////////////////////////////////////////////////////////

	    		
	    	    
	    	    ///////////////////////////页面级////////////////////////////////////////
	    		//返回
	    		$rootScope.goBack = function(event) {
	    			window.history.go(-1);
	    		}
	    	    ///////////////////////////页面级////////////////////////////////////////

	    		/////////////////////////////////////////////////////////////////////////////////////////////
	    		function GetQueryString(name) {
	    		    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	    		    var r = window.location.search.substr(1).match(reg);
	    		    if (r != null) return unescape(r[2]); 
	    		    return null;
	    		}
	    		
	    		//读取cookies
	    		function getCookie(name)
	    		{
	    			var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
	    			if(arr=document.cookie.match(reg))
	    				return unescape(arr[2]);
	    			else
	    				return null;
	    		}
	    		
	    		//BizData统一处理ajax错误
	    		$rootScope.ajaxError = function(XMLHttpRequest, textStatus, errorThrown){
		           	console.log('ajax.error.XMLHttpRequest-->>',XMLHttpRequest);
		        	console.log('ajax.error.textStatus-->>',textStatus);
		        	console.log('ajax.error.errorThrown-->>',errorThrown);
		            //通常情况下textStatus和errorThrown只有其中一个包含信息
		            //this;   //调用本次ajax请求时传递的options参数
		           	if(XMLHttpRequest.readyState==0 && XMLHttpRequest.status==0){
		           		alert("ajax调用失败！请检查服务器是否启动，或者网络连接是否存在问题！");
		           	}else if(XMLHttpRequest.readyState==4 && XMLHttpRequest.status==500){
		           		//Internal Server Error
		           		alert("ajax调用失败！服务内部错误，需要软件供应商解决！");
		           	}else{
		            	alert("ajax调用失败！"+"readyState:"+XMLHttpRequest.readyState+",status:"+XMLHttpRequest.status);
		           	}
	    		};
	    		$rootScope.ajaxComplete = function(XMLHttpRequest, textStatus){
		           	//console.log('ajax.complete.XMLHttpRequest-->>',XMLHttpRequest);
		        	//XMLHttpRequest.responseJSON:请求成功：json数据，停止服务器：undefined，无权限时：没有出现这个项目
		        	//XMLHttpRequest.redyState:请求成功：4，停止服务器：0，无权限时：4
		        	//XMLHttpRequest.status:请求成功：200，停止服务器：0，无权限时：200
		        	//XMLHttpRequest.statusText:请求成功："OK"，停止服务器："error"，无权限时："OK"
		        	//console.log('ajax.complete.textStatus-->>',textStatus);
		        	//textStatus:请求成功：success,停止服务器：error，无权限时：parsererror（由于要求返回json（dataType），但返回的是html）
		            //this;    //调用本次ajax请求时传递的options参数
		        	if(XMLHttpRequest.responseJSON && XMLHttpRequest.responseJSON.code){
		            	if(XMLHttpRequest.responseJSON.code==-999){
		            		//未登录
		            		alert(XMLHttpRequest.responseJSON.msg);
		            		window.location.href = $rootScope.getProjectName() + "/blogin";
		            	}
		            	if(XMLHttpRequest.responseJSON.code==-998){
		            		//未授权
		            		alert(XMLHttpRequest.responseJSON.msg);
		            	}
		        	}
	    		};
	    		
	    		//从地址栏获取token
	    		$rootScope.getAccessToken = function() {
	    			return $rootScope.access_token;
	    		}
	    		
//	    		$rootScope.access_token = GetQueryString('access_token');
	    		$rootScope.access_token = getCookie('token');
	    		$rootScope.sLoginName = getCookie('sLoginName');
	    		console.log('$rootScope.sLoginName-->',$rootScope.sLoginName );
			      
	    		//设置ajax全局请求token
	    		
	    		$.ajaxSetup({
	    			contentType: "application/json; charset=utf-8",
	    			beforeSend: function (evt, request) {
						$.LoadingOverlay("show");

//	    		    	console.log('ajaxSetup.evt-->',evt);
//	    		    	console.log('ajaxSetup.request-->',request);
	    		    	/*
	    		        var accessToken = getAccessToken();
	    		        if (accessToken != null) {
	    		            var data = 'access_token=' + accessToken;
	    		            if (request.url.indexOf('?')) {
	    		                data = '?' + data;
	    		            }
	    		            request.url += data;
	    		        }
	    		        */
//	                    var access_token = 'Bearer ' + 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJyb290IiwiZXhwIjoxNTI5Mzc0NDg3LCJ1c2VybmFtZSI6InJvb3QiLCJpYXQiOjE1MjY3ODI0ODd9.ZvmPZFL3uVRdasH7BKXFHTsqG62CPyVvaW8JbUNeeOs';
//    		    		console.log(request.url.indexOf('/backcenter'));
//	    		    	if(request.url.indexOf('/backcenter')!=-1){
//		    		    	evt.setRequestHeader("access_token", $rootScope.access_token);
//	    		    	}
	    		    },
	    		    error: function(XMLHttpRequest, textStatus, errorThrown) {
	    		    	$rootScope.ajaxError(XMLHttpRequest, textStatus, errorThrown);
	    		    },
	    		    complete: function(XMLHttpRequest, textStatus){
						$.LoadingOverlay("hide");
	    		    	$rootScope.ajaxComplete(XMLHttpRequest, textStatus);
	    			}
	    		});
	    		
	    		/////////////////////////////////////////////////////////////////////////////////////////////
	    		//检查当前公司是否存在，不存在则跳回中心页面
	    		$rootScope.checkTopMyOgn = function(){
	    	        if(!$rootScope.topMyOgn){
	    				var to = '/backcenter/home/center';
	    				var params = {};
	    				var options = {};//{"reload":true};
	    				$state.go(to,params,options);
	    	        }else{
	    	        	return true;
	    	        }
	    	    };
	    	    	    		
	    	    
			    }
			  ]
			)
    
	app.config(['$httpProvider', function($httpProvider){
    	//console.log('$httpProvider-->',$httpProvider);
	    //$httpProvider.interceptors.push(httpInterceptor);
		//设置angularjs全局请求token
		$httpProvider.interceptors.push(['$q' ,'$injector', '$rootScope', function ($q ,$injector, $rootScope) {
            var httpInterceptor = {
                'responseError' : function(response) {
                    // todo...
                    return $q.reject(response);
                },
                'response' : function(response) {
                    if (response.status == 21000) {
                        // console.log('do something...');
                    }
                    return response || $q.when(response);
                },
                'request' : function(config) {
//                	console.log('config-->',config);
                    config.headers = config.headers || {};
//                  var access_token = 'Bearer ' + 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJyb290IiwiZXhwIjoxNTI5Mzc0NDg3LCJ1c2VybmFtZSI6InJvb3QiLCJpYXQiOjE1MjY3ODI0ODd9.ZvmPZFL3uVRdasH7BKXFHTsqG62CPyVvaW8JbUNeeOs';
                    config.headers.Authorization = $rootScope.access_token;
                    
                    return config || $q.when(config);
                    // return config;
                },
                'requestError' : function(config){
                    // todo...
                    return $q.reject(config);
                }
            };
            return httpInterceptor;
        }]);
	}])		
	
			
//	app.config(function($stateProvider, $urlRouterProvider) {
	app.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
		//配置$http请求、响应拦截器
//		$httpProvider.interceptors.push(TokenInterceptor);
		  //

	      /////////////////////////////
	      // Redirects and Otherwise //
	      /////////////////////////////

	      // Use $urlRouterProvider to configure any redirects (when) and invalid urls (otherwise).
	      $urlRouterProvider

	        // The `when` method says if the url is ever the 1st param, then redirect to the 2nd param
	        // Here we are just setting up some convenience urls.
	        .when('/c?id', '/contacts/:id')
	        .when('/user/:id', '/contacts/:id')

	        // If the url is ever invalid, e.g. '/asdf', then redirect to '/' aka the home state
	        .otherwise('/backcenter/home/center');
		  // For any unmatched url, redirect to /state1
//		  $urlRouterProvider.otherwise("/backcenter/home/center");
		  //

	      //////////////////////////
	      // State Configurations //
	      //////////////////////////

	      // Use $stateProvider to configure your states.
		  // Now set up the states
		  $stateProvider
		    .state('/backcenter/home/center', {
		      url: "/backcenter/home/center",
		      templateUrl: "home/center",
		      controller : 'centerCtrl as Model'
		    })
			.state('/backcenter/person/list', {
		      url: "/backcenter/person/list",
		      templateUrl: "person/list",
			  controller : 'personListCtrl as Model'
		      ,resolve:{
		          loadMyCtrl:function ($ocLazyLoad) {
		              return $ocLazyLoad.load({
	//				      name:'childApp',
		                  files:["js/person/list"]
		              })
		           }
		       }
		    })
			.state('/backcenter/password/page', {
				url: "/backcenter/password/page",
				templateUrl : "password/page",
				controller : 'passwordCrtl as Model'
				    ,resolve:{
			             loadMyCtrl:function ($ocLazyLoad) {
			                 return $ocLazyLoad.load({
//				                     name:'childApp',
			                     files:["js/password/page.js"]
			                 })
			             }
			         }
			})
		    .state('/backcenter/sysInfo/tree', {
		      url: "/backcenter/sysInfo/tree",
		      templateUrl: "sysInfo/tree",
		      cache: false,
			  controller : 'sysInfoTreeCtrl as Model'
		      ,resolve:{
		          loadMyCtrl:function ($ocLazyLoad) {
		              return $ocLazyLoad.load({
	//				      name:'childApp',
		                  files:["js/sysInfo/tree.js"]
		              })
		           }
		       }
		    })

		    .state('/backcenter/billSetting/list', {
		      url: "/backcenter/billSetting/list?:recordState,:id,:systemCode,:systemName,:appId,:appName",
		      templateUrl: "billSetting/list",
			  controller : 'billSettingListCtrl as Model'
		      ,resolve:{
		          loadMyCtrl:function ($ocLazyLoad) {
		              return $ocLazyLoad.load({
	//				      name:'childApp',
		                  files:["js/billSetting/list"]
		              })
		           }
		       }
		    })
		    .state('/backcenter/sysAction/list', {
		      url: "/backcenter/sysAction/list",
		      templateUrl: "sysAction/list",
		      cache: false,
			  controller : 'sysActionCtrl as Model'
		      ,resolve:{
		          loadMyCtrl:function ($ocLazyLoad) {
		              return $ocLazyLoad.load({
	//				      name:'childApp',
		                  files:["js/sysAction/list.js"]
		              })
		           }
		       }
		    })
			
		    .state('/backcenter/ogn/list', {
		      url: "/backcenter/ogn/list?:recordState,:id,:name",
		      templateUrl: "ogn/list",
			  controller : 'ognListCtrl as Model'
				    ,resolve:{
			             loadMyCtrl:function ($ocLazyLoad) {
			                 return $ocLazyLoad.load({
//				                     name:'childApp',
			                     files:["js/ogn/list.js"]
			                 })
			             }
			         }
		    })
		    .state('/backcenter/ogn/center', {
		      url: "/backcenter/ogn/center?:recordState,:id,:name",
		      templateUrl: "ogn/center",
			  controller : 'ognCenterCtrl as Model'
				    ,resolve:{
			             loadMyCtrl:function ($ocLazyLoad) {
			                 return $ocLazyLoad.load({
//				                     name:'childApp',
			                     files:["js/ogn/center.js"]
			                 })
			             }
			         }
		    })
		    .state('/backcenter/org/single', {
		      url: "/backcenter/org/single?:recordState,:id,:title",
		      templateUrl: "org/single",
			  controller : 'ognSingleCtrl as Model'
				    ,resolve:{
			             loadMyCtrl:function ($ocLazyLoad) {
			                 return $ocLazyLoad.load({
//				                     name:'childApp',
			                     files:["js/org/single.js"]
			                 })
			             }
			         }
		    })
			
			
		    .state('/backcenter/org/tree', {
		      url: "/backcenter/org/tree?:recordState,:id",
		      templateUrl: "org/tree",
			  controller : 'orgTreeCtrl as Model'
				    ,resolve:{
			             loadMyCtrl:function ($ocLazyLoad) {
						    console.log('aaaa');
			                 return $ocLazyLoad.load({
//				                     name:'childApp',
			                     files:["js/org/tree.js"]
			                 })
			             }
			         }
		    })
		    .state('/backcenter/role/list', {
		      url: "/backcenter/role/list?:recordState,:id",
		      templateUrl: "role/list",
			  controller : 'roleListCtrl as Model'
				    ,resolve:{
			             loadMyCtrl:function ($ocLazyLoad) {
			                 return $ocLazyLoad.load({
//				                     name:'childApp',
			                     files:["js/role/list.js"]
			                 })
			             }
			         }
		    })
		    .state('/backcenter/permission/list', {
		      url: "/backcenter/permission/list?:roleName,:roleID",
		      templateUrl: "permission/list",
			  controller : 'permissionListCtrl as Model'
				    ,resolve:{
			             loadMyCtrl:function ($ocLazyLoad) {
			                 return $ocLazyLoad.load({
//				                     name:'childApp',
			                     files:["js/permission/list.js"]
			                 })
			             }
			         }
		    })
		    .state('/backcenter/orgauth/list', {
		      url: "/backcenter/orgauth/list?:recordState,:id",
		      templateUrl: "orgauth/list",
			  controller : 'orgauthCtrl as Model'
				    ,resolve:{
			             loadMyCtrl:function ($ocLazyLoad) {
			                 return $ocLazyLoad.load({
//				                     name:'childApp',
			                     files:["js/orgauth/list.js"]
			                 })
			             }
			         }
		    })

		    .state('/backcenter/monitor/server', {
		      url: "/backcenter/monitor/server",
		      templateUrl: "monitor/server",
			  controller : 'serverCtrl as Model'
			      ,resolve:{
			          loadMyCtrl:function ($ocLazyLoad) {
			              return $ocLazyLoad.load({
		//				      name:'childApp',
			                  files:["js/monitor/server"]
			              })
			           }
			       }
		    })
		    
		    .state('/backcenter/regionInfo/tree', {
		      url: "/backcenter/regionInfo/tree",
		      templateUrl: "regionInfo/tree",
			  controller : 'regionInfoTreeCtrl as Model'
		      ,resolve:{
		          loadMyCtrl:function ($ocLazyLoad) {
		              return $ocLazyLoad.load({
	//				      name:'childApp',
		                  files:["js/regionInfo/tree"]
		              })
		           }
		       }
		    })
		    .state('/backcenter/tradeInfo/tree', {
		      url: "/backcenter/tradeInfo/tree",
		      templateUrl: "tradeInfo/tree",
			  controller : 'tradeInfoTreeCtrl as Model'
		      ,resolve:{
		          loadMyCtrl:function ($ocLazyLoad) {
		              return $ocLazyLoad.load({
	//				      name:'childApp',
		                  files:["js/tradeInfo/tree"]
		              })
		           }
		       }
		    })
		    .state('/backcenter/expressInfo/list', {
		      url: "/backcenter/expressInfo/list",
		      templateUrl: "expressInfo/list",
			  controller : 'expressInfoListCtrl as Model'
		      ,resolve:{
		          loadMyCtrl:function ($ocLazyLoad) {
		              return $ocLazyLoad.load({
	//				      name:'childApp',
		                  files:["js/expressInfo/list"]
		              })
		           }
		       }
		    })
		    
		    
		    
		    .state('state1', {
			  url: "/state1",
			  templateUrl: "partials/state1.html"
			})
			.state('state1.list', {
		      url: "/list",
		      templateUrl: "partials/state1.list.html",
		      controller: function($scope) {
		        $scope.items = ["A", "List", "Of", "Items"];
		      }
		    })
		    .state('state2', {
		      url: "/state2",
		      templateUrl: "partials/state2.html"
		    })
		    .state('state2.list', {
		      url: "/list",
		      templateUrl: "partials/state2.list.html",
		      controller: function($scope) {
		        $scope.things = ["A", "Set", "Of", "Things"];
		      }
		    })
		    
//			.state('test', {
//		      url: "/test",
//		      templateUrl: "messages/list",
//			  controller : 'TestCtrl as Model'
//			  ,resolve: f.resolve
//		    })
		    
		    ;
		});	
	
	/*
	function f($rootScope,$scope,$state,securityService,  BizData ) {
		var Model = this;
		//console.log('用户中心默认页面center控制器运行完成!');
		return Model;
	}	

	//按需加载
	f.resolve = {
		delay: function($q) {
			var delay = $q.defer(),
			load = function(){
				console.log(';aldfs');
				$.getScript('js/center/center.js',function(){
					delay.resolve();
				});
			};
			load();
			return delay.promise;
		}
	}   
	
	app.controller('TestCtrl',['$rootScope', '$scope', '$state', 'securityService', 'BizData', f])//控制器结束
	*/
	
	return app;
});
